package com.shanzmoo.core.util;

import com.shanzmoo.core.pay.sdk.wxpay.WXPayConstants;
import com.shanzmoo.core.pay.sdk.wxpay.WXPayUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 自定义微信支付工具类
 *
 * @author: Gzhao 2020/12/11
 */
@Slf4j
public class SWxPayUtils {
    private SWxPayUtils() {
    }


    /**
     * 获取微信回调成功返回结果
     *
     * @return
     */
    public static String getWxpayCallbackSuccessReturn() {
        StringBuilder stb = new StringBuilder();
        stb.append("<xml>");
        stb.append("<return_code><![CDATA[SUCCESS]]></return_code>");
        stb.append("<return_msg><![CDATA[OK]]></return_msg>");
        stb.append("</xml> ");
        return stb.toString();
    }

    /**
     * 获取微信回调失败返回结果
     *
     * @return
     */
    public static String getWxpayCallbackFailReturn(String msg) {
        StringBuilder stb = new StringBuilder();
        stb.append("<xml>");
        stb.append("<return_code><![CDATA[FAIL]]></return_code>");
        stb.append("<return_msg><![CDATA[");
        stb.append(msg);
        stb.append("]]></return_msg>");
        stb.append("</xml> ");
        return stb.toString();
    }


    /**
     * 将微信支付回调结果处理成map，并设置签名类型
     * @param notifyData
     * @return
     * @throws Exception
     */
    public static Map<String,String> convertMapAndSignType(String notifyData) throws Exception {
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);
        addSignType(notifyMap);

        return notifyMap;
    }

    /**
     * 设置签名类型
     *
     * @param notifyMap
     */
    public static void addSignType(Map<String, String> notifyMap) {
        notifyMap.put(WXPayConstants.FIELD_SIGN_TYPE, WXPayConstants.HMACSHA256);
    }

    /**
     * 微信支付回调结果处理
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static String obtainNotifyData(HttpServletRequest request) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        StringBuilder stb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            stb.append(line);
        }
        br.close();
        String notityXml = stb.toString();
        log.info("接收到的报文：{}", notityXml);
        return notityXml;
    }

}
